package me.wpf.utils;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.security.UserGroupInformation;


/**
 * Description: hive客户端
 *
 * @author 王朋飞
 * @create 2019/11/6
 */
public class HiveClient {
    private static Properties prop = ConfigPropertiesUtil.getConfigProperties();
    private static String driverName = prop.getProperty("hive.driverName");
    private static String Url = prop.getProperty("hive.url");
    private static String uName = prop.getProperty("hive.username", null);
    private static String uPwd = prop.getProperty("hive.passwd", null);
    private static String kerberosUser = prop.getProperty("hive.kerberos.user", null);
    private static Connection conn = null;


    /**
     * 开启连接
     *
     * @return
     */
    public static Connection initConnnection() {
        try {
            if (conn == null || conn.isClosed())
                //认证kerberos
                authKrb5();
            Class.forName(driverName);
            if (uName != null && uPwd != null) {
                conn = DriverManager.getConnection(Url, uName, uPwd);
            } else {
                conn = DriverManager.getConnection(Url);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            System.exit(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void authKrb5() {
        // 设置jvm启动时krb5的读取路径参数
        System.setProperty("java.security.krb5.conf", "src/main/resources/krb5.conf");
        // 配置kerberos认证
        Configuration conf = new Configuration();
        conf.setBoolean("hadoop.security.authorization", true);
        conf.set("hadoop.security.authentication", "kerberos");
        // System.out.println(System.getProperty("java.security.krb5.conf"));
        UserGroupInformation.setConfiguration(conf);
        try {
            UserGroupInformation.loginUserFromKeytab(
                    kerberosUser,
                    "src/main/resources/asmp.keytab");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void CloseConnection(Connection conn, ResultSet rs, PreparedStatement ps) {
        if (ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }

}
